﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Model
{
    /// <summary>
    /// Http请求帮助类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <param name="url">请求地址，支持https</param>
        /// <param name="timeout">超时默认2分钟（180000）</param>
        /// <param name="header">请求头</param>
        /// <returns>响应结果</returns>
        public static async Task<string> GetToStringAsyn(string url,int timeout = 180000,WebHeaderCollection header = null)
        {
            // 创建http请求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.KeepAlive = false;

            request.Timeout = timeout;
            request.ReadWriteTimeout = timeout;

            if(header != null)
                request.Headers = header;

            // 获取响应消息
            var resp = await request.GetResponseAsync() as HttpWebResponse;

            // 请求成功
            if(resp.StatusCode == HttpStatusCode.OK)
            {
                using (StreamReader sr = new StreamReader(resp.GetResponseStream(),Encoding.UTF8))
                {
                    // 读取响应文本
                    var str = await sr.ReadToEndAsync();
                    return str;
                }
            }
            else
            {
                throw new Exception($"Http status code is:{resp.StatusCode}");
            }
        }

        /// <summary>
        /// HTTP文件下载
        /// </summary>
        /// <param name="uri">下载源地方</param>
        /// <param name="savePath">保存地址</param>
        public static  long DownloadFile(string uri,string savePath)
        {
            try
            {
                using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write))
                {
                    HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
                    using (Stream stream = request.GetResponse().GetResponseStream())
                    {
                        byte[] buffer = new byte[8 * 1024];
                        int len = stream.Read(buffer, 0, buffer.Length);
                        while (len > 0)
                        {
                            fs.Write(buffer, 0, len);
                            len = stream.Read(buffer, 0, buffer.Length);
                        }

                        return len;
                    }
                }
            }
            catch (Exception)
            {
                File.Delete(savePath);
                throw;
            }
        }
    }
}
